<template>
  <view class="addTask">
    <NavBar
      v-if="appInfoStore().isH5"
      title="新建任务"
      :backgroundColor="'#F0FBFF'"
    />
    <view
      class="content"
      :class="{ 'padding-top-navbar': appInfoStore().isH5 }"
    >
      <view class="title">
        <view class="title-img">
          <view class="title-img-logo">
            <img
              src="https://img.alicdn.com/imgextra/i2/1034622205/O1CN01TULwic1S9wNQzJN95_!!1034622205.png"
              alt=""
            />
          </view>
          <view class="title-img-text">
            <view class="title-img-text-name">
              <text>若是紧急任务,将第一时间接收变动通知</text>
              <text>你设定的团队任务, 是大家共同奋斗的方向</text>
            </view>
          </view>
        </view>
      </view>
      <view class="describe">
        <view class="describe-title">
          <!-- 后期约定带图标，暂时图标占位 -->
          <img
            src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN014R3FM51S9wNSkBlq9_!!1034622205.png"
            alt=""
          />
          <nut-input
            v-model="form.title"
            labelwidth="0"
            placeholder="请输入任务标题"
          />
        </view>
        <view class="describe-text">
          <nut-textarea
            v-model="form.content"
            placeholder="添加描述..."
            :rows="3"
            :count="false"
          />
        </view>
      </view>
      <view class="addTask-form">
        <!-- <nut-form
          :model-value="form.state"
          ref="dynamicRefForm"
          :rules="rules"
          > -->
        <view class="addTask-form-item">
          <view class="addTask-form-title">
            <text>优先级</text>
            <text>*</text>
          </view>
          <view class="addTask-form-input">
            <nut-radio-group
              v-model="form.priorityLevel"
              @change="onRadioChange"
              direction="horizontal"
            >
              <nut-radio
                :label="idx + 1"
                v-for="(itm, idx) in priorityLevelList"
                :key="idx"
                >{{ itm.text }}</nut-radio
              >
            </nut-radio-group>
            <!-- <radio-group @change="onRadioChange">
              <label
                v-for="item in priorityLevelList"
                class="checkbox-list__label"
                :key="item.value"
              >
                <radio
                  color="#033a91"
                  class="checkbox-list__checkbox"
                  :value="item.value"
                  :checked="item.checked"
                  >{{ item.text }}</radio
                >
              </label>
            </radio-group> -->
          </view>
        </view>
        <view class="addTask-form-item">
          <view class="addTask-form-title">
            <text>完成时间</text>
          </view>
          <view class="addTask-form-input">
            <view class="picker">
              <view
                class="picker-today-stop"
                @click="handleTodayStop"
              >
                <text>今天 截止</text>
                <i class="iconfont icon-lingdang"></i>
              </view>
              <i
                class="iconfont icon-cha"
                style="color: #999"
                @click="deleteTodayStop"
              ></i>
            </view>
            <view
              class="picker-box"
              @click="onDateChange"
            >
              <!-- {{ completionTime }} -->
              <view class="picker"> {{ completionTime }} <i class="iconfont icon-xiajiantou"></i> </view>
            </view>

            <!-- <picker
              mode="date"
              @change="onDateChange"
            >
              <view class="picker-box">
                <view class="picker"> {{ completionTime }} <i class="iconfont icon-xiajiantou"></i> </view>
              </view>
            </picker> -->
          </view>
        </view>
        <view class="addTask-form-item">
          <view class="addTask-form-title">
            <text>执行人</text>
            <text>*</text>
          </view>
          <view class="addTask-form-user">
            <view class="selected-user">已选择：{{ executorUsers ? executorUsers?.length : 0 }}人</view>
            <view class="add-selected-user">
              <view
                v-if="executorUsers?.length > 0"
                class="add-selected-user-avatar"
                @click="addViewPerson('executor')"
              >
                <nut-avatar-group
                  max-count="4"
                  zIndex="right"
                  size="small"
                >
                  <nut-avatar
                    v-for="itm in executorUsers"
                    :key="itm.deptId"
                    size="small"
                    :url="itm.avatarUrls"
                  >
                    <img
                      :src="itm.avatarUrls"
                      alt=""
                    />
                  </nut-avatar>
                </nut-avatar-group>
                <text v-if="executorUsers?.length == 1">{{ executorUsers[0]?.nickName }}</text>
                <text v-else>{{ executorUsers ? executorUsers?.length : 0 }}人负责</text>
                <i
                  style="font-size: 14px"
                  class="iconfont icon-cha"
                ></i>
              </view>
              <view
                class="add-selected-user-icon"
                @click="addUser('executor')"
              >
                <nut-button
                  plain
                  type="info"
                >
                  <i
                    class="iconfont icon-jiahao1"
                    style="font-size: 20px"
                  ></i>
                </nut-button>
              </view>
            </view>
          </view>
        </view>
        <view class="addTask-form-item">
          <view class="addTask-form-title">
            <text>协作人员</text>
            <text>*</text>
          </view>
          <view class="addTask-form-user">
            <view class="selected-user">已选择：{{ collaboratorUsers ? collaboratorUsers?.length : 0 }}人</view>
            <view class="add-selected-user">
              <view
                v-if="collaboratorUsers?.length > 0"
                class="add-selected-user-avatar"
                @click="addViewPerson('collaborator')"
              >
                <nut-avatar-group
                  max-count="4"
                  zIndex="right"
                  max-content=" "
                  size="small"
                >
                  <nut-avatar
                    v-for="itm in collaboratorUsers"
                    :key="itm.deptId"
                    size="small"
                  >
                    <img
                      :src="itm.avatarUrls"
                      alt=""
                    />
                  </nut-avatar>
                </nut-avatar-group>
                <text v-if="collaboratorUsers?.length == 1">{{ collaboratorUsers[0]?.nickName }}</text>
                <text v-else>{{ collaboratorUsers ? collaboratorUsers?.length : 0 }}人负责</text>
                <i
                  style="font-size: 14px"
                  class="iconfont icon-cha"
                ></i>
              </view>
              <view
                class="add-selected-user-icon"
                @click="addUser('collaborator')"
              >
                <nut-button
                  plain
                  type="info"
                >
                  <i
                    class="iconfont icon-jiahao1"
                    style="font-size: 20px"
                  ></i>
                </nut-button>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="addTask-other-form">
        <view class="addTask-other-form-box">
          <view class="addTask-other-title">
            <text>其他信息</text>
            <text>（非必填）</text>
          </view>
          <view class="addTask-other-form-item">
            <view class="addTask-form-title">
              <text>可见范围</text>
            </view>
            <view>
              <view class="addTask-form-input">
                <radio-group @change="visibleScopeChange">
                  <label
                    v-for="item in visibleScopeList"
                    class="checkbox-list__label"
                    :key="item.value"
                  >
                    <radio
                      color="#033a91"
                      class="checkbox-list__checkbox"
                      :value="item.value"
                      :checked="item.checked"
                      >{{ item.text }}</radio
                    >
                  </label>
                </radio-group>
              </view>
              <view class="addTask-other-form-notice">* 全部成员可见，仅部门负责人可编辑</view>
            </view>
          </view>
          <view class="addTask-other-form-item">
            <view class="addTask-form-title">
              <text>附件</text>
            </view>
            <!-- 附件 -->
            <uploads
              @files="getFiles"
              :path="officeTaskFiles"
            >
              <img
                src="https://img.alicdn.com/imgextra/i1/1034622205/O1CN01uiKNUZ1S9wNlJIpdn_!!1034622205.png"
                alt=""
              />
              <text>添加附件</text>
            </uploads>
          </view>
          <view class="addTask-other-form-item">
            <view class="addTask-form-title">
              <text>关联任务</text>
            </view>
            <view
              class="addTask-form-upload"
              v-if="false"
            >
              <img
                src="https://img.alicdn.com/imgextra/i4/1034622205/O1CN01Vr1EEQ1S9wNS8dH1r_!!1034622205.png"
                alt=""
              />
              <text>选择任务</text>
            </view>
            <view
              class="addTask-related-tasks"
              v-else
            >
              <view class="related-tasks1">
                <text>齐心协力，一起加油</text>
                <!-- <view class="related-tasks1-icon">
                  <i class="iconfont icon-rili"></i>
                  <img
                    src="https://img.alicdn.com/imgextra/i4/1034622205/O1CN01Vr1EEQ1S9wNS8dH1r_!!1034622205.png"
                    alt=""
                  />
                  <i class="iconfont icon-youjiantou1"></i>
                </view> -->
              </view>
              <view
                class="related-tasks2-box"
                v-for="item in relatedtasksSelectedList"
                :key="item"
              >
                <view class="related-tasks2">
                  <text>{{ item.title }}</text>
                </view>
                <view class="related-tasks3">
                  <view class="related-tasks3-left">
                    <text>负责人</text>
                    <view class="related-avatar">
                      <nut-avatar-group
                        max-count="3"
                        zIndex="right"
                        max-content=" "
                        size="small"
                      >
                        <nut-avatar
                          v-for="(itm, idx) in item.responsible"
                          :key="idx"
                          size="small"
                        >
                          <img
                            :src="itm.avatarUrl"
                            alt=""
                          />
                        </nut-avatar>
                      </nut-avatar-group>
                      <text
                        class="related-avatar-text"
                        v-if="item.responsible?.length == 1"
                        >{{ item.responsible[0]?.nickName }}</text
                      >
                      <text v-else>{{ item.responsible ? item.responsible?.length : 0 }}人负责</text>
                    </view>
                  </view>
                  <view class="related-tasks3-right">
                    <text
                      >截止{{ item.dealTime?.substring(5, 10)
                      }}<i
                        class="iconfont icon-cha"
                        @click="deleteTasksSelected(item)"
                      ></i
                    ></text>
                  </view>
                </view>
              </view>
              <view
                class="related-tasks-btn"
                @click="handleTasks"
              >
                <img
                  src="https://img.alicdn.com/imgextra/i2/1034622205/O1CN01sgDQ9t1S9wNkcoP2b_!!1034622205.png"
                  alt=""
                />
                <text>关联任务</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="addTask-bottom">
        <view class="addTask-bottom-logo">
          <img
            src="https://img.alicdn.com/imgextra/i2/1034622205/O1CN01ROtCca1S9wNLeJ6zx_!!1034622205.png"
            alt=""
          />
        </view>
      </view>
      <view class="addTask-btn">
        <view class="addTask-btn-box">
          <view class="addTask-btn-left">
            <view class="addTask-btn-logo">
              <!-- <nut-circle-progress
                :progress="30"
                :radius="30"
                :stroke-width="10"
                :clockwise="false"
                class="no-percentage"
              > -->
              <view class="addTask-btn-logo-box">
                <img
                  src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN01UTcfwW1S9wNtmA6Q6_!!1034622205.png"
                  alt=""
                />
              </view>
              <!-- </nut-circle-progress> -->
            </view>
            <view class="addTask-btn-text">
              <text>{{ priorityLevelList[form.priorityLevel - 1]?.text }}</text>
              <text>高效利用时间</text>
            </view>
          </view>
          <view
            class="addTask-btn-button"
            @click="submit"
          >
            <nut-button
              color="#1E74FD"
              shape="round"
              size="small"
            >
              <img
                src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN01lJcTqk1S9wNSdCs9Q_!!1034622205.png"
                alt=""
              />
              {{ isEdit ? "保存" : "创建" }}任务
            </nut-button>
          </view>
        </view>
      </view>
    </view>
    <nut-popup
      position="bottom"
      round
      v-model:visible="showPicker"
    >
      <nut-date-picker
        v-model="datePicker"
        type="datetime"
        :three-dimensional="false"
        @confirm="finishTimeConfirm"
      ></nut-date-picker>
      <!-- :min-date="min" -->
      <!-- :formatter="formatter" -->
    </nut-popup>
    <addUserPopup
      :isUserPopup="isUserPopup"
      @update:visible="updateVisible"
      @selectedUsers="handleSelectedUsers"
      :feedbackUsers="addUesrType == 'executor' ? executorUsers : collaboratorUsers"
      :disabledList="[...executorUsers, ...collaboratorUsers]"
    />
    <viewPersonPopup
      :isviewPersonPopup="isviewPersonPopup"
      @selectedUsers="handleSelectedUsers"
      @update:visible="viewVisible"
      :feedbackUsers="addUesrType == 'executor' ? executorUsers : collaboratorUsers"
    />
    <relatedtasksPopup
      :isRelatedtasksPopup="isRelatedtasksPopup"
      @update:visible="relatedtasksVisible"
      @selecteList="handleTasksSelected"
      :feedbackTasks="relatedtasksSelectedList"
    />
  </view>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import NavBar from "@/components/navBar/index.vue";
import { userInfoStore } from "@/stores/userInfoStore";
import relatedtasksPopup from "@/components/relatedtasksPopup/index.vue";
import addUserPopup from "@/components/addUserPopup/index.vue";
import viewPersonPopup from "@/components/viewPersonPopup/index.vue";
import { formatDates } from "@/utils/utils";
import qiniuUpload from "@/utils/qiniuUploader";
import uploads from "@/components/uploads/index.vue";
import { getTokens, addSystemTask, editSystemTask, queryTask, getSystemtaskList } from "@/api/index";
import Taro, { useRouter } from "@tarojs/taro";
import { appInfoStore } from "@/stores/appInfo";
import { ITask, ITaskForm } from "./type";
const router = useRouter();
console.log(router.params.type, "router. params");
const isEdit = ref(false);
const min = new Date(2020, 0, 1, 10, 40);
const isUserPopup = ref(false); // 是否显示用户弹窗
const isviewPersonPopup = ref(false); // 是否显示查看用户弹窗
const isRelatedtasksPopup = ref(false); // 是否显示关联任务弹窗
const showPicker = ref(false);
const qiniuToken = ref("");
const selectdTask = ref();
// 当前选中的文件
const currentFile = ref();
const addUesrType = ref("");
const uploadUrl = ref("");
const officeTaskFileList = ref([]);
const officeTaskFiles = ref([]); //回显上传的文件
const executorUsers = ref([]); //执行人
const collaboratorUsers = ref([]); //协作人员
const datePicker = ref(new Date());
const initFormData: ITaskForm = {
  title: undefined,
  content: undefined,
  priorityLevel: 1, //优先级
  dealTime: "", //完成时间
  executorNameList: [], //执行人
  visibleScope: "1", //可见范围
  officeTaskFileList: [], //附件
};
const data = reactive<PageData<ITaskForm>>({
  form: { ...initFormData },
});
const { form } = toRefs(data);
const show = ref(false);
//如何默认当前时间为2025-05-26格式
const completionTime = ref("选择时间");

const relatedtasksSelectedList = ref([]); // 关联任务列表
onMounted(async () => {
  isEdit.value = router.params.type == "edit";
  console.log(form.value, "form.value");

  if (isEdit.value) {
    await handleTaskPermissionList();
    await getQueryTask();
    Taro.setNavigationBarTitle({
      title: "编辑任务",
    });
  }
});
//今天截止
const handleTodayStop = () => {
  let now = formatDates(new Date());
  completionTime.value = now;
  //获取当前时间日期时分秒
  form.value.dealTime =
    new Date().toLocaleDateString().replace(/\//g, "-") +
    " " +
    new Date().getHours() +
    ":" +
    new Date().getMinutes() +
    ":00";
  console.log(form.value.dealTime, "form.value.dealTime");
};
// 删除今天截止
const deleteTodayStop = () => {
  completionTime.value = "选择时间";
  form.value.dealTime = "";
};
// 关联所有任务获取列表
const handleTaskPermissionList = async () => {
  // meetingState: 2,
  let params = {};
  await getSystemtaskList(params).then(res => {
    let rows = res.rows;
    relatedtasksSelectedList.value = rows.filter(i => i.taskId == router.params.taskId);
    console.log(selectdTask.value, "rows");
  });
};
// 查询回显任务数据
const getQueryTask = async () => {
  await queryTask(router.params.taskId).then(res => {
    form.value = Object.assign(form.value, res.data);
    relatedtasksSelectedList.value = res.data.parentTaskId ? res.data.relatedTaskList : [];
    completionTime.value = res.data.dealTime.split(" ")[0];
    executorUsers.value = res.data?.executorNameList;
    collaboratorUsers.value = res.data.collaboratorsNameList ?? [];
    officeTaskFiles.value = res.data.filesList;
    officeTaskFiles.value = officeTaskFiles.value?.map(i => {
      return { name: i.name, url: i.files };
    });
    console.log(officeTaskFiles.value, "form.valuedata");
    console.log(executorUsers.value, "executorUsers.value");
    console.log(collaboratorUsers.value, "collaboratorUsers.value");
  });
};

// 选中完成时间
const finishTimeConfirm = ({ selectedValue }) => {
  completionTime.value = selectedValue[0] + "-" + selectedValue[1] + "-" + selectedValue[2];
  form.value.dealTime =
    selectedValue[0] +
    "-" +
    selectedValue[1] +
    "-" +
    selectedValue[2] +
    " " +
    selectedValue[3] +
    ":" +
    selectedValue[4] +
    ":00";
  console.log(form.value.dealTime, "form.value.dealTime");

  showPicker.value = false;
};
// 打开关联任务列表
const handleTasks = () => {
  isRelatedtasksPopup.value = true;
};
// 关联任务列表选中
const handleTasksSelected = (val: any) => {
  relatedtasksSelectedList.value = val;
};
const formatter = (type: any, option: { text: string }) => {
  switch (type) {
    case "year":
      option.text += "年";
      break;
    case "month":
      option.text += "月";
      break;
    case "day":
      option.text += "日";
      break;
    case "hour":
      option.text += "时";
      break;
    case "minute":
      option.text += "分";
      break;
    default:
      option.text += "";
  }
};
// 删除关联选择
const deleteTasksSelected = item => {
  relatedtasksSelectedList.value = relatedtasksSelectedList.value.filter(i => i.taskId !== item.taskId);
};
const relatedtasksVisible = (val: boolean) => {
  isRelatedtasksPopup.value = val;
};
const getFiles = async (files: any) => {
  files.forEach((item: any) => {
    form.value.officeTaskFileList.push({
      name: item.name,
      files: item.url,
    });
  });
};
const handleSelectedUsers = (val: any) => {
  if (addUesrType.value == "executor") {
    executorUsers.value = val;
  }
  if (addUesrType.value == "collaborator") {
    collaboratorUsers.value = val;
  }
};
// 添加人员
const addUser = (type: any) => {
  addUesrType.value = type;
  isUserPopup.value = true;
};
const updateVisible = (val: boolean) => {
  isUserPopup.value = val;
};
// 查看人员
const addViewPerson = (type: any) => {
  addUesrType.value = type;
  isviewPersonPopup.value = true;
};

const viewVisible = (val: boolean) => {
  isviewPersonPopup.value = val;
};
const onDateChange = (e: { detail: { value: string } }) => {
  console.log(showPicker.value);

  showPicker.value = true;
  // completionTime.value = e.detail.value;
  // form.value.dealTime = e.detail.value;
};
// 选中的优先级
const onRadioChange = e => {
  console.log(e, "e666");

  // form.value.priorityLevel = e.detail.value;
};
//
const visibleScopeChange = (e: { detail: { value: any } }) => {
  form.value.visibleScope = e.detail.value;
};
// 提交
const submit = () => {
  if (!form.value.title) {
    Taro.showToast({
      title: "请输入任务标题",
      icon: "none",
    });
    return;
  }
  if (!form.value.dealTime) {
    Taro.showToast({
      title: "请选择截止时间",
      icon: "none",
    });
    return;
  }
  if (executorUsers.value.length == 0) {
    Taro.showToast({
      title: "请选择执行人",
      icon: "none",
    });
    return;
  }
  if (collaboratorUsers.value.length == 0) {
    Taro.showToast({
      title: "请选择协作人员",
      icon: "none",
    });
    return;
  }

  let newexecutorList: any = [];
  let collaboratorList: any = [];
  executorUsers.value.map((item: any) => {
    return newexecutorList.push({
      nickName: item.nickName,
      userId: item.userId,
    });
  });
  collaboratorUsers.value.map((item: any) => {
    return collaboratorList.push({
      nickName: item.nickName,
      userId: item.userId,
    });
  });
  let params = {
    ...form.value,
    executorNameList: newexecutorList,
    collaboratorsNameList: collaboratorList,
    parentTaskId: relatedtasksSelectedList.value[0]?.parentTaskId || "",
  };
  console.log(relatedtasksSelectedList.value, "relatedtasksSelectedList.value[0]");

  console.log(params, "params");
  if (isEdit.value || form.value.taskId) {
    params = {
      ...form.value,
      executorNameList: newexecutorList,
      collaboratorsNameList: collaboratorList,
      parentTaskId: relatedtasksSelectedList.value[0]?.parentTaskId || "",
      officeTaskFileList: form.value?.officeTaskFileList.map(i => {
        return { name: i.name, files: i.files };
      }),
    };
    editSystemTask(params).then((res: any) => {
      if (res.code == 200) {
        Taro.showToast({
          title: "编辑成功",
          icon: "success",
        });
        setTimeout(() => {
          Taro.navigateBack();
        }, 1000);
      }
    });
  } else {
    addSystemTask(params).then((res: any) => {
      if (res.code == 200) {
        Taro.showToast({
          title: "创建成功",
          icon: "success",
        });
        setTimeout(() => {
          Taro.navigateBack();
        }, 1000);
      }
    });
  }
};
const currentDate = ref(new Date());
const visibleScopeList = ref([
  {
    value: "1",
    text: "私有",
    checked: false,
  },
  {
    value: "2",
    text: "公开",
    checked: true,
  },
]);
const priorityLevelList = ref([
  {
    value: "1",
    text: "S级",
    checked: true,
  },
  {
    value: "2",
    text: "A级",
    checked: false,
  },
  {
    value: "3",
    text: "B级",
    checked: false,
  },
]);
const rules = {
  name: [
    {
      required: true,
      message: "请输入姓名",
      trigger: "blur",
    },
  ],
};
</script>

<style lang="less">
@import "./index.less";
// @import url("../../../assets/css/index.css");
@import "@/assets/css/index.less";
</style>
